package com.itpan.Utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.itpan.Entity.Product;
import com.itpan.Service.CustomerService;
import com.itpan.Service.ProductService;

import java.util.ArrayList;
import java.util.List;

public class ProductExcelListener extends AnalysisEventListener<Product> {

    private final ProductService productService;

    private final CustomerService customerService;
    private List<Product> productList = new ArrayList<>();

    private final EntityValidate entityValidate;

    public ProductExcelListener(ProductService productService, CustomerService customerService, EntityValidate entityValidate) {
        this.productService = productService;
        this.customerService = customerService;
        this.entityValidate = entityValidate;
    }

    @Override
    public void invoke(Product product, AnalysisContext context) {
        // 校验数据是否有效
        if (isValidProduct(product) && !isAlreadyRegistered(product)&&isExitCustomer(product) && entityValidate.isValidateOfProduct(product)) {
            productList.add(product);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 读取结束后的操作，可以进行批量保存或其他处理
        if (!productList.isEmpty()) {
            productService.saveAll(productList);
        }
    }

    private boolean isValidProduct(Product product) {
        // 检查每个字段是否为null或空
        return product.getProductName() != null
                && product.getProductDescription() != null
                && product.getProductName() != null
                && product.getSupplierID() != null
                && product.getUnitPrice() != null;

    }

    /*
    判断该字段的id是否已经注册

     */

    private boolean isAlreadyRegistered(Product product) {
        Product existingProduct = productService.getById(product.getProductID());
        return existingProduct != null;
    }


    private  boolean isExitCustomer(Product product){
        return customerService.getById(product.getSupplierID())!=null;
    }
}
